<template>
<div>
  <el-form :model="form" :rules="rules" ref="form" label-width="100px">
    <!-- 基本信息 -->
    <el-row>
      <el-col :span="8">
        <el-form-item label="省" prop="province" >
           <el-select v-model="form.province" @change="upCity" placeholder="请选择" :disabled="isDisabled">
             <el-option
               v-for="item in Province"
               :key="item.id"
               :label="item.gname"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="市" prop="city" >
           <el-select v-model="form.city" @change="findcity" placeholder="请选择" :disabled="isDisabled">
             <el-option
               v-for="item in city"
               :key="item.id"
               :label="item.gname"
               :value="item.id">
             </el-option>
           </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="代理商" prop="agent" >
          <el-input v-model="form.agent" :disabled="isDisabled"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="商品名称" prop="goodsName" >
          <el-input v-model="form.goodsName" maxlength="20" @change="name" :disabled="isDisabled"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="金额" prop="amount" >
          <el-input v-model="form.amount" :disabled="isDisabled" @input="validateAmountInput"></el-input>
        </el-form-item>
      </el-col>

    </el-row>
    <el-row>
      
      <el-col :span="12">
        <el-form-item label="商品类型" prop="goodsType" >
          <el-checkbox-group v-model="goodsType" :disabled="isDisabled">
            <el-checkbox label="玩具"></el-checkbox>
            <el-checkbox label="电子"></el-checkbox>
            <el-checkbox label="书籍"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="商品颜色" prop="goodsColor" >
          <el-checkbox-group v-model="goodsColor" :disabled="isDisabled">
            <el-checkbox label="红色"></el-checkbox>
            <el-checkbox label="绿色"></el-checkbox>
            <el-checkbox label="蓝色"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-col>

    </el-row>
    <el-row>
      
      <el-col :span="12">
        <el-form-item label="发布时间" prop="creationTime" >
          <el-date-picker v-model="form.creationTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:ss:mm" :disabled="isDisabled"></el-date-picker>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择" :disabled="isDisabled">
            <el-option label="上架" value="0"></el-option>
            <el-option label="下架" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="所属人" prop="operator" >
          <el-input v-model="form.operator" :disabled="isDisabled"></el-input>
        </el-form-item>
      </el-col>
    </el-row>


    <!-- 商品描述 -->
    <el-row>
      <el-col :span="24">
        <el-form-item label="商品描述" prop="goodsDescription" >
          <el-input type="textarea" v-model="form.goodsDescription" :disabled="isDisabled" @focus="openDialog()"></el-input>
        </el-form-item>
      </el-col>
    </el-row>


    <!-- 预览图 -->
    <el-row>
      <el-col :span="8">
        <el-form-item label="预览图" >
         <el-upload
             class="avatar-uploader"
             action="/api/upload"
             :show-file-list="false"
             :on-success="handleAvatarSuccess"
             :before-upload="beforeAvatarUpload"
             :headers="uploadHeaders"
             :disabled="isDisabled">
             <img v-if="code" :src="form.imga" class="avatar">
             <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item >
          <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handl"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
              :disabled="isDisabled">
              <img v-if="cod" :src="form.imgb" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item >
         <el-upload
             class="avatar-uploader"
             action="/api/upload"
             :show-file-list="false"
             :on-success="handleAvatar"
             :before-upload="beforeAvatarUpload"
             :headers="uploadHeaders"
             :disabled="isDisabled">
             <img v-if="co" :src="form.imgc" class="avatar">
             <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 联系方式 -->
    <el-row>
      <el-col :span="24" >
        <el-form-item label="联系方式" >
            <el-button type="primary" style="float : right" @click="AddContact" :disabled="isDisabled">新增</el-button>
        </el-form-item>
        
      </el-col>
    </el-row>

      <el-row  v-for="(item,index) in addContact" :key="index" >

        <el-col :span="6">
          <el-form-item label="姓名" prop="name" :rules="{
            required: true, message: '姓名不能为空', trigger: 'blur'
          }">
            <el-input v-model="item.name" :disabled="isDisabled" id="name" name="name" maxlength="5" pattern="/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/" required></el-input>
              </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电话" prop="phone" :rules="{
            required: true, message: '电话不能为空', trigger: 'blur'
          }">
            <el-input v-model="item.phone" :disabled="isDisabled" id="phone" name="phone" pattern="/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/" required></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮箱" prop="email" :rules="{
            required: true, message: '邮箱不能为空', trigger: 'blur',
          }">
            <el-input v-model="item.email" :disabled="isDisabled" id="email" name="email" pattern="^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$" required></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" >
           <el-button type="text" @click="addContact.splice(index,1)" style="margin-left: 50px;" :disabled="isDisabled">删除</el-button>
        </el-col>
      </el-row>


          <!-- 备注 -->
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark" >
                <el-input type="textarea" v-model="form.remark" :disabled="isDisabled"></el-input>
              </el-form-item>

              
            </el-col>
          </el-row>


          <!-- 按钮 -->
          <el-row>
            <el-col :span="24" > 
              <el-button type="primary" @click="submitForm('form')" :disabled="isDisabled">提交</el-button>
              <el-button @click="resetForm('form')" :disabled="isDisabled">重置</el-button>
            </el-col>
          </el-row>
        </el-form>



        <!-- 新增与修改 -->
        <el-row>
          <el-col :span="20" :offset="4"><div class="grid-content bg-purple-dark">

            <el-dialog  :visible.sync="dialogFormVisible">
               <div class="item">
                 <MyEditor
                   id="editor"
                   ref="editor"
                   :wordNum="TiLength"
                   v-model="form.goodsDescription"
                   @change="onEditorChange($event)"
                 >
                 </MyEditor>
                 <p v-if="warnShow" class="warnText">
                   编辑内容不能超过20个字!
                 </p>
                 <span class="wordNumber ">{{ TiLength }}/20</span>
               </div>
            </el-dialog>

          </div></el-col>
        </el-row>





      </div>
    </template>


    <script>
    import { getToken } from '@/util/auth';
    import MyEditor from "@/components/MyEditor/editor.vue";
import axios from 'axios';
    export default {
        components: {
          MyEditor
        },
      data() {

        var validateAmount = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('金额不能为空'));
            } else {
                const reg = /^\d+(\.\d{1,2})?$/;
                if (!reg.test(value)) {
                    callback(new Error('请输入正确的金额格式，最多保留两位小数'));
                } else {
                    callback();
                }
            }          
        };

      //  var validateChinese = (rule, value, callback) => {
      //    if (!value) {
      //      return callback(new Error('请输入内容'));
      //    } else {
      //      const reg = /^[\u4e00-\u9fa5]{1,5}$/;
      //      if (!reg.test(value)) {
      //        callback(new Error('请输入1到5个汉字'));
      //      } else {
      //        callback();
      //      }
      //    }
      //  };

        // var validatePhone =(rule, value, callback) =>{
        //   if (!value) {
        //     return callback(new Error('请输入手机号'));
        //   } else {
        //     const reg = /^1[3-9]\d{9}$/;
        //     if (!reg.test(value)) {
        //       callback(new Error('请输入有效的手机号'));
        //     } else {
        //       callback();
        //     }
        //   }
        // };
        
        

        return {
            uploadHeaders:{"Authorization": getToken()}, //获取登录值

            id:"",
          TypeList:[],
          colorList:[],
          Province:[],
          city:[],
          goodsType:[],
          goodsColor:[],
          form: {

           "affiliation": "",
           "agent": "",
           "amount": "",
           "city": "",
           "creationTime": "",
           "endDate": "",
           "fakeDelete": "",
           "goodsColor": "",
           "goodsDescription": "",
           "goodsName": "",
           "goodsType": "",
           "id": 0,
           "imga": "",
           "imgb": "",
           "imgc": "",
           "operatingTime": "",
           "operator": "",
           "province": "",
           "sheng": "",
           "shi": "",
           "startDate": "",
           "state": "",
           goodsText:'',
           remark:'',
           addContact:[]
          },
          fileList1: [],
          fileList2: [],
          fileList3: [],
          addContact:[], //联系
          code:false,
          cod:false,
          co:false,
          isDisabled:false,
          
          dialogFormVisible: false, //新增弹窗
          rules: {
            province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
            city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
            agent: [{ required: true, message: '请输入代理商', trigger: 'blur' }],
            goodsName: [
              { required: true, message: '请输入商品名称', trigger: 'blur' },
              { min: 0, max: 20, message: '长度不能超过20个字符', trigger: 'blur' }
            ],
            amount: [
              { validator: validateAmount, trigger: 'blur' }
            ],
            goodsType: [
            { required: true, message: '请输入商品类型', trigger: 'change' },
              { validator: this.validateSingleSelection, trigger: 'change' }
            ],
            goodsColor: [
              { required: true, message: '请输入商品颜色', trigger: 'blur' }
            ],
            state: [
              { required: true, message: '请选择状态', trigger: 'change' }
            ],
            remark:[
            { required: true, message: '请输入备注', trigger: 'blur' },
            { max: 255, message: '长度不能超过255个字符', trigger: 'blur' }
            ]
            
             

          },
          TiLength: 0,
          warnShow: false,
          editorHtml: null
        };
      },
      created(){
        this.initProvince()
        this.id = sessionStorage.getItem("id")
        console.log(this.id);
        if(this.id){
          this.getGoods()
          this.isDisabled = true
        }
      },
      methods: {
        //商品类型验证
        validateSingleSelection(rule, value, callback) {
          if (value.length !== 1) {
            callback(new Error('只能选择一项'));
          } else {
            callback();
          }
        },
        

        


        //回显
        getGoods(){
            axios.get("/api/goods/findTbGoodsById?id="+this.id).then(res=>{
              this.form = res.data.data
              console.log("111:", this.form);
              console.log("addTask:", res.data.data.addContact);
              this.goodsColor=this.form.goodsColor.split(",")
              this.goodsType = this.form.goodsType.split(",")
              this.addContact =  res.data.data.addContact
              this.code = true;
              this.cod = true;
              this.co = true;
              this.form.province = res.data.data.sheng
              this.form.city = res.data.data.shi
              this.initProvince();


            })
            sessionStorage.removeItem("id")
        },

        submitForm(form) {
          this.$refs[form].validate((valid) => {
            if (valid) {
              alert('submit!');
              this.add()//新增
            } else {
              console.log('error submit!!');
              return false;
            }
          });
        },
        resetForm(form){
          this.$nextTick(()=>{
            this.$refs[form].resetFields();
          });
        },



        //新增
        add() {
            this.form.addContact = this.addContact
            this.form.goodsColor=this.goodsColor.join(",")
            this.form.goodsType=this.goodsType.join(",")
          // 提交表单逻辑
          console.log('提交表单', this.form);
         axios.post("/api/goods/addTbGoods",this.form).then(res=>{
           //弹框
           this.$message({
                      message: res.data.message,
                      type: 'success'
                    });
         })
        },
        //联系方式
        AddContact(){
            this.addContact.push({
                name:'',
                phone:'',
                email:''
            })
            console.log('aaa',this.addContact);
            
        },

        openDialog(){
            this.dialogFormVisible=true
        },


        name(val){
          if (val > 20) {
              alert("商品名称不能超过20个字")
          }
        },        
        
        //省
        initProvince(){
            axios.get("/api/goods/findProvinceList",).then(res=>{
                this.Province = res.data.data
            })
        },
        upCity(val){
            this.initcity(val)
            console.log("id",val);
        },
        findcity(val){
           console.log("市", val);
            console.log(val);

        },
        initcity(val){
            axios.get("/api/goods/findCityList?id="+val).then(res=>{
                this.city = res.data.data
            })
        },
        handlePreview(file) {
          console.log(file);
        },
        handleRemove(file) {
          console.log(file);
        },
       
       

        //图片上传
        handleAvatarSuccess(res, file) {

        this.form.imga = file.response.data

        this.code = true;
        console.log(this.form.imga)

        },
        

        //图片上传
        handl(res, file) {

        this.form.imgb = file.response.data

        this.cod = true;
        console.log(this.form.imga)

        },
       

        //图片上传
        handleAvatar(res, file) {

        this.form.imgc = file.response.data

        this.co = true;
        console.log(this.form.imga)
                                                                                                                   
        },
        //复选框
        onEditorChange(e) {
           this.form.goodsDescription=e.replace(/<p>\s*<\/p>/g, '').replace(/^<p>(.*)<\/p>$/, '$1')      
          console.log( this.form.goodsDescription, "aaa");


          var reg = /<[^<>]+>/g; //去标签
          // var reg = /<(?!img).*?>/g //去除img以外的所有标签
          var value = e.replace(reg, "");
          value = value.replace(/&nbsp;/gi, ""); //将空格全部替换
          this.TiLength = value.length; //文字长度显示
          console.log(this.TiLength, "  this.TiLength");
          if (this.TiLength <= 20) {
            this.editorHtml = e;
            console.log(this.editorHtml, "this.editorHtml");
          }
          if (this.TiLength > 20) {
            //当长度大于10时,只截取10之前的内容并赋值
            this.$nextTick(() => {
              this.form.content = this.editorHtml;
            });
            this.warnShow = true;
            // this.$message.error("文字最多输入10字!");
            return false;
          }
        }
        
      }
    };
    </script>


    <style scoped>
    .el-row {
      margin-bottom: 10px;
    }

    avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .upload-demo {
      margin-bottom: 20px;
    }


    .item {
      margin-top: 30px;
      width: 800px;
      position: relative;
    }
    .wordNumber {
      color: #909399;
      background: #fff;
      text-align: right;
      z-index: 100;
      right: 10px;
      bottom: 5px;
      font-size: 12px;
      position: absolute;
    }
    .warnText {
      font-size: 14px;
      color: red;
      text-align: left;
    }
    </style>